//子函数 实现上传文件；
#include"../include/p.h"
#include<stdio.h>

int c_Upload(int tcp_socket,const char *filename)
{
	char buf[100]={0};
	//1 获得文件大小stat
	struct stat statbuff;
	printf("%s",filename);
	if(-1==stat(filename,&statbuff))
	{
		printf("stat wrong \n");
	}
	else 
	{
		int filesize=statbuff.st_size;
		printf("stat ok ,the file size is %d\n",filesize);

	}
	int filesize=statbuff.st_size;
	//将文件大小转为字符串存入buf中
	sprintf(buf,"%d",filesize);

	//2 注意粘包问题
	sleep(1);
	//3 把文件大小传给服务器端
	send(tcp_socket,buf,strlen(buf),0);
	printf("大小上传成功 \n");
	
	//清空buf
	memset(buf,'\0',sizeof(buf));

	//接收服务器端的回应
	recv(tcp_socket,buf,sizeof(buf),0);
	printf("服务器端回应：%s\n",buf);

	//打开文件
	int fr=open(filename,O_RDONLY);
	if(fr<0)
	{
		perror("open error\n");
		return -1;
	}
	while(1)
	{	
		memset(buf,'\0',sizeof(buf));
		
		int n=read(fr,buf,sizeof(buf));
		if(n==0)
		{
			close(fr);
			break;
		}
		send(tcp_socket,buf,n,0);
	}
	printf("文件上传成功\n");
	return 0;	
	
}
